<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>小方块阵列</title>
  <style>
    body {
      background: #000;
    }

    #container {
      width: 600px;
      margin: 100px auto;
      display: flex;
      flex-wrap: wrap;
    }

    .square {
      width: 10px;
      height: 10px;
      background: rgba(38, 37, 37, 0.658);
      margin-right: 2px;
      margin-bottom: 2px;
      transition: 1s;
    }

    .square:hover {
      transition: 0s;
    }
  </style>
</head>

<body>
  <!--小方块阵列-->
  <div class="container" id="container"></div>
  <script>

    generateSquare()

    //生成一个小方块阵列，并且给每个小方块绑定鼠标移入和移出事件
    function generateSquare() {
      const container = document.getElementById("container");
      for (let i = 0; i < 3000; i++) {
        const square = document.createElement("div");
        square.className = "square";
        container.appendChild(square);
      }
      container.onmouseover = function (e) {
        let target = e.target;
        if (target.className == "square") {
          setColor(target)
        }
      }
      container.onmouseout = function (e) {
        let target = e.target;
        if (target.className == "square") {
          deleteColor(target)
        }
      }
    }
    //这个函数实现设置小方块颜色，并且绑定到鼠标移入事件
    function setColor(element) {
      console.log(Math.floor(Math.random() * 256));//[0-1)  => [0,256)  =>  [0,255]
      // // element.style.backgroundColor = 'rbg(' + (Math.floor(Math.random() * 256) + ' , , )'
      // let num1 = Math.floor(Math.random() * 256);
      // let num2 = Math.floor(Math.random() * 256);
      // let num3 = Math.floor(Math.random() * 256);
      function getNum() {
        return Math.floor(Math.random() * 256)
      }
      element.style.backgroundColor = `rgb(${getNum()},${getNum()},${getNum()})`
    }

    //这个函数实现去除小方块颜色，并且绑定到鼠标移出事件
    function deleteColor(element) {
      // element.style.transition = '1s'
      element.style.backgroundColor = ''
    }
  </script>
</body>

</html>